package com.waa.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.rabbitmq.client.Channel;
import com.waa.gulimall.common.to.mq.OrderTo;
import com.waa.gulimall.common.to.mq.StockDetailTo;
import com.waa.gulimall.common.to.mq.StockLockTo;
import com.waa.gulimall.common.utils.R;
import com.waa.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.waa.gulimall.ware.entity.WareOrderTaskEntity;
import com.waa.gulimall.ware.exception.NoStockException;
import com.waa.gulimall.ware.feign.OrderFeignService;
import com.waa.gulimall.ware.feign.ProductFeignService;
import com.waa.gulimall.ware.service.WareOrderTaskDetailService;
import com.waa.gulimall.ware.service.WareOrderTaskService;
import com.waa.gulimall.ware.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.waa.gulimall.common.utils.PageUtils;
import com.waa.gulimall.common.utils.Query;

import com.waa.gulimall.ware.dao.WareSkuDao;
import com.waa.gulimall.ware.entity.WareSkuEntity;
import com.waa.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;


@Service("wareSkuService")
@Slf4j
@RabbitListener
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    private WareSkuDao wareSkuDao;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;
    @Autowired
    private WareOrderTaskService wareOrderTaskService;
    @Autowired
    private OrderFeignService orderFeignService;

    private void unLockStock(Long skuId, Long wareId, Integer num, Long tasDeatilId) {
        //库存解锁
        wareSkuDao.unLockStock(skuId, wareId, num);
        //更新库存工作单的状态
        final WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity();
        wareOrderTaskDetailEntity.setId(tasDeatilId);
        wareOrderTaskDetailEntity.setLockStatus(2);//状态变为2
        wareOrderTaskDetailService.updateById(wareOrderTaskDetailEntity);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        final QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)) {
            wrapper.eq("sku_id", skuId);
        }
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            wrapper.eq("ware_id", wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void wareHousing(Long skuId, Long wareId, Integer skuNum) {
        //判断库存中有没有这个sku，如果没有就新建，有就入库
        final List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        //判断没有就新建一个
        if (wareSkuEntities.size() == 0 || wareSkuEntities == null) {
            final WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            //TODO 远程查询sku的名字 如果失败整个事务无需回滚
            try {
                final R info = productFeignService.info(skuId);
                System.out.println(info.get("skuInfo"));
                final Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");
                if (info.getCode() == 0) {
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {
                log.info("远程查询sku的名字失败，但不影响操作");
            }
            wareSkuDao.insert(wareSkuEntity);
        } else {
            wareSkuDao.addStock(skuId, wareId, skuNum);
        }

    }

    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {


        final List<SkuHasStockVo> stockVoList = skuIds.stream().map(skuId -> {
            final SkuHasStockVo stockVo = new SkuHasStockVo();
            //查询当前的库存总量
            Long count = baseMapper.getSkuStock(skuId);
            stockVo.setSkuId(skuId);
            stockVo.setHasStock(count == null ? false : count > 0);
            return stockVo;
        }).collect(Collectors.toList());

        return stockVoList;
    }


    /**
     * 为某个订单锁定库存
     *
     * @param vo
     * @return
     */
    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {
        /**
         * 保存库存工作单详情
         */
        final WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(wareOrderTaskEntity);
        //按照我下单的收货地址，找到一个就近仓库，锁定仓库
        //找到每个商品在那个仓库都有库存
        final List<OrderItemVo> locks = vo.getLocks();
        final List<SkuWareHasStock> stocks = locks.stream().map(item -> {
            final SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
            skuWareHasStock.setSkuId(item.getSkuId());
            //查询在哪里有库存
            List<Long> wareIds = this.baseMapper.listWareIdHasSkuStock(item.getSkuId());
            skuWareHasStock.setWareId(wareIds);
            skuWareHasStock.setNum(item.getCount());
            return skuWareHasStock;
        }).collect(Collectors.toList());
        //锁定库存
        for (SkuWareHasStock stock : stocks) {
            boolean skuStocked = false;
            final Long skuId = stock.getSkuId();
            final List<Long> wareId = stock.getWareId();
            final Integer num = stock.getNum();
            if (wareId == null || wareId.size() == 0) {
                //没有任何库存
                throw new NoStockException(skuId);
            }
            //1.如果每一个商品都锁定成功，将当前商品锁定了几件的工作单记录发给mq
            //2.如果锁定失败前面保存的工作单信息就回滚了
            for (Long aLong : wareId) {
                final Long res = wareSkuDao.lockSkuStock(skuId, aLong, num);
                if (res == 1) {
                    //锁成功
                    skuStocked = true;
                    //TODO 告诉MQ库存锁定成功
                    final WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity(null, skuId, "", stock.getNum(), wareOrderTaskEntity.getId(), aLong, 1);
                    wareOrderTaskDetailService.save(wareOrderTaskDetailEntity);
                    final StockLockTo stockLockTo = new StockLockTo();
                    stockLockTo.setId(wareOrderTaskEntity.getId());
                    final StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(wareOrderTaskDetailEntity, stockDetailTo);
                    //只发id不行
                    stockLockTo.setDetailId(stockDetailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", stockLockTo);
                    break;
                } else {
                    //锁失败，重试下一个仓库
                }
            }
            if (skuStocked == false) {
                //当前商品所有仓库都没有锁定
                throw new NoStockException(skuId);
            }
        }
        //3.能走到这里肯定是全部成功了
        return true;
    }

    @Override
    public void unLockStock(StockLockTo to) {

        final StockDetailTo stockDetai = to.getDetailId();
        final Long detailId = stockDetai.getId();//库存工作单id
        /**
         * 解锁
         * 1.查数据库关于这个订单的锁定信息
         * 有：证明库存锁定成功了
         *   解锁:订单情况
         *          1.没有这个订单。必须解锁
         *          2.有这个订单。不是解锁库存
         *              订单状态： 已取消：解锁库存
         *                        没取消：不能解锁
         *   没有：库存锁定失败，库存回滚了。这种情况无需解锁
         *
         */
        final WareOrderTaskDetailEntity detailEntity = wareOrderTaskDetailService.getById(stockDetai);

        if (detailEntity != null) {
            //解锁
            final Long id = to.getId();
            final WareOrderTaskEntity orderTaskEntity = wareOrderTaskService.getById(id);
            final String orderSn = orderTaskEntity.getOrderSn();//根据订单号来查询订单状态
            final R r = orderFeignService.getOrderStatus(orderSn);
            if (r.getCode() == 0) {
                //订单数据返回
                final OrderVo orderVo = (OrderVo) r.getData(new TypeReference<OrderVo>() {
                });

                if (orderVo == null || orderVo.getStatus() == 4) {
                    //订单被取消了，所以要解锁库存
                    if (detailEntity.getLockStatus() == 1) {
                        unLockStock(stockDetai.getSkuId(), stockDetai.getWareId(), stockDetai.getSkuNum(), detailId);
                    }
                }
            } else {
                //消息拒绝后从新放到队列让别人继续消费
                throw new RuntimeException("远程服务失败");
            }
        } else {
            //无需解锁
        }

    }

    //防止订单服务卡顿，导致订单状态一直改不了，库存消息优先到期，查库存状态新建状态,什么都不错就走了
    //导致卡顿的订单永远不能解锁
    @Override
    public void unLockStock(OrderTo orderTo) {
        final String orderSn = orderTo.getOrderSn();
        //查询一下最新库存的状态，防止重复额解锁库存
     WareOrderTaskEntity wareOrderTaskEntity = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        final Long entityId = wareOrderTaskEntity.getId();
        //按照工作单，找到所有没有解锁的库存，进行解锁
        final List<WareOrderTaskDetailEntity> list = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                .eq("lock_status", 1));
        for (WareOrderTaskDetailEntity entity : list) {
            unLockStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum(),entity.getId());
        }


    }
//    @Override
//    public void unLockStock(StockLockTo to) {
//        try {
//
//
//            System.out.println("收到解锁库存的消息");
//            final StockDetailTo stockDetai = to.getDetailId();
//            final Long detailId = stockDetai.getId();//库存工作单id
//            /**
//             * 解锁
//             * 1.查数据库关于这个订单的锁定信息
//             * 有：证明库存锁定成功了
//             *   解锁:订单情况
//             *          1.没有这个订单。必须解锁
//             *          2.有这个订单。不是解锁库存
//             *              订单状态： 已取消：解锁库存
//             *                        没取消：不能解锁
//             *   没有：库存锁定失败，库存回滚了。这种情况无需解锁
//             *
//             */
//            final WareOrderTaskDetailEntity detailEntity = wareOrderTaskDetailService.getById(stockDetai);
//
//            if (detailEntity != null){
//                //解锁
//                final Long id = to.getId();
//                final WareOrderTaskEntity orderTaskEntity = wareOrderTaskService.getById(id);
//                final String orderSn = orderTaskEntity.getOrderSn();//根据订单号来查询订单状态
//                final R r = orderFeignService.getOrderStatus(orderSn);
//                if (r.getCode() == 0){
//                    //订单数据返回
//                    final OrderVo orderVo = (OrderVo) r.getData(new TypeReference<OrderVo>() {
//                    });
//
//                    if (orderVo == null||orderVo.getStatus() == 4){
//                        //订单被取消了，所以要解锁库存
//                        unLockStock(stockDetai.getSkuId(),stockDetai.getWareId(),stockDetai.getSkuNum(),detailId);
//                        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
//                    }
//                }else {
//                    //消息拒绝后从新放到队列让别人继续消费
//                    channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
//                }
//            }else {
//                //无需解锁
//                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
//            }
//        }catch (Exception e){
//            //消息拒绝后无需消费重新放到队列里面，让别人继续消费解锁
//            System.out.println("错误..."+e.getMessage());
//            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
//
//        }
//    }
}